﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using YiSha.Util;
using YiSha.Util.Model;

namespace YiSha.Admin.WebApi.Controllers
{
    /// <summary>
    /// 小程序接口
    /// </summary>
    public class WeiXinController : ControllerBase
    {
        private const string appid = "wx031cf8272cd345a1";
        private const string secret = "424abc11020e69a7f8ea9e500c29b3b3";

        /// <summary>
        /// 微信登录
        /// </summary>
        /// <param name="jscode"></param>
        /// <returns></returns>
        [HttpPost]
        public TData<string> WxLogin([FromForm] string jscode)
        {
            TData<string> result = new TData<string>();
            string _posdata = $"appid={appid }&secret={secret}&js_code={ jscode}&grant_type=authorization_code";
            LogHelper.Info(_posdata);
            string _url = "https://api.weixin.qq.com/sns/jscode2session";//获取openid
            result.Data = request_url(_url, _posdata);
            if (result.Data.Contains("\"openid\""))
            {
                //dynamic _modal = Newtonsoft.Json.Linq.JToken.Parse(_data) as dynamic;
                result.Tag = 1;
                //result.Data = _data;
            }
            return result;
        }

        /// <summary>
        /// 获取手机号
        /// </summary>
        /// <param name="session_key"></param>
        /// <param name="ency"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        [HttpPost]
        public TData<string> GetPhoneNumber([FromForm] string session_key, [FromForm] string ency, [FromForm] string iv)
        {
            TData<string> result = new TData<string>() { Tag = 0, Message = "没有获取到手机号" };
            if (!String.IsNullOrEmpty(ency) && !string.IsNullOrEmpty(iv))
            {
                //解析手机号码
                string _telPhone = getPhoneNumber(ency, iv, session_key);
                result.Tag = 1;
                result.Data = _telPhone;
            }

            return result;
        }

        #region 请求api

        /// <summary>
        /// 请求api
        /// </summary>
        /// <param name="_url"></param>
        /// <param name="post_data"></param>
        /// <returns></returns>
        private string request_url(string _url, string post_data)
        {
            string result = "";
            string url = _url;

            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "application/json";
            //request.Headers=""
            request.Method = "POST";

            byte[] buffer = encoding.GetBytes(post_data.Trim());
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

        #endregion 请求api

        /// <summary>
                /// AES解密：从小程序中 getPhoneNumber 返回值中，解析手机号码
                /// </summary>
                /// <param name="encryptedData">包括敏感数据在内的完整用户信息的加密数据，详细见加密数据解密算法</param>
                /// <param name="IV">加密算法的初始向量</param>
                /// <param name="Session_key"></param>
                /// <returns>手机号码</returns>
        private string getPhoneNumber(string encryptedData, string IV, string Session_key)
        {
            byte[] encryData = Convert.FromBase64String(encryptedData);  // strToToHexByte(text);
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            rijndaelCipher.Key = Convert.FromBase64String(Session_key); // Encoding.UTF8.GetBytes(AesKey);
            rijndaelCipher.IV = Convert.FromBase64String(IV);// Encoding.UTF8.GetBytes(AesIV);
            rijndaelCipher.Mode = CipherMode.CBC;
            rijndaelCipher.Padding = PaddingMode.PKCS7;
            ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
            byte[] plainText = transform.TransformFinalBlock(encryData, 0, encryData.Length);
            string result = Encoding.Default.GetString(plainText);
            //动态解析result 成对象
            dynamic model = Newtonsoft.Json.Linq.JToken.Parse(result) as dynamic;
            return model.phoneNumber;
        }
    }
}
